package com.hd123.rumba.gwt.widget.client.grid;

import com.hd123.rumba.gwt.base.client.Format;

public class DxGridColumnSummaryProvider implements DxGridSummaryProvider {
  DxGridDataProvider provider;
  int[] methods = new int[10];

  public DxGridColumnSummaryProvider(DxGridDataProvider provider) {
    setProvider(provider);
  }

  public void setSummaryMethod(int col, int method) {
    if (col >= methods.length) {
      int[] m = new int[col + 1];
      for (int i = 0; i < methods.length; ++i)
        m[i] = methods[i];
      methods = m;
    }
    methods[col] = method;
  }

  public void setProvider(DxGridDataProvider provider) {
    this.provider = provider;
  }

  public String getData(int col) {
    String result = "";
    switch (methods[col]) {
    case COUNT:
      result = "计数: " + Integer.toString(provider.getRowCount());
      break;
    case SUM:
      if (provider.getRowCount() > 0) {
        double sum = 0;
        for (int row = 0; row < provider.getRowCount(); ++row) {
          try {
            sum += Double.parseDouble(provider.getData(row, col));
          } catch (Exception e) {
          }
        }
        result = "合计: " + Format.MONEY_FORMAT.format(sum);
      }
      break;
    case AVERAGE:
      if (provider.getRowCount() > 0) {
        double sum = 0;
        for (int row = 0; row < provider.getRowCount(); ++row) {
          try {
            sum += Double.parseDouble(provider.getData(row, col));
          } catch (Exception e) {
          }
        }
        result = "平均: " + Format.MONEY_FORMAT.format(sum / provider.getRowCount());
      }
      break;
    case MAX:
      if (provider.getRowCount() > 0) {
        double max = 0;
        try {
          max = Double.parseDouble(provider.getData(0, col));
        } catch (Exception e) {
        }
        for (int row = 0; row < provider.getRowCount(); ++row) {
          try {
            double me = Double.parseDouble(provider.getData(row, col));
            if (max < me)
              max = me;
          } catch (Exception e) {
          }
        }
        result = "最大: " + Format.MONEY_FORMAT.format(max);
      }
      break;
    case MIN:
      if (provider.getRowCount() > 0) {
        double min = 0;
        try {
          min = Double.parseDouble(provider.getData(0, col));
        } catch (Exception e) {
        }
        for (int row = 0; row < provider.getRowCount(); ++row) {
          try {
            double me = Double.parseDouble(provider.getData(row, col));
            if (min > me)
              min = me;
          } catch (Exception e) {
          }
        }
        result = "最小: " + Format.MONEY_FORMAT.format(min);
      }
      break;
    }
    return result;
  }
}
